// let baseUrl = "http://localhost:8080/";
$(function () {
    getCourseClassify();
    getCourses();
});

//获取课程分类
function getCourseClassify() {
    $.post({
        url: baseUrl+"education_api/courseClassify/query",
        data: {},
        success: function (result) {
            applyCourseClassify(result)
        }
    }, 'json');
}

let courseClassifyId = null;
let charge = null;
let state = 0;

//根据需求获取课程(courseClassifyid:课程类型；charge:是否免费（免费:0，收费:1）；state:(0-上架，1-下架，2-待上架))
function getCourses() {
    $.post({
        url: baseUrl+"education_api/course/query",
        data: {courseClassifyId: courseClassifyId, charge: charge, state: state},
        success: function (result) {
            applyCourses(result);
        }
    }, 'json');
}

//渲染课程分类
function applyCourseClassify(result) {
    let courseLabelContainer = $(".course-label");

    let array = result.data;


    let template = "";
    for (let i = 0; i < array.length; i++) {
        let CourseClassifyTemplate = $(".CourseClassifyTemplate").html().replaceAll("{{CourseClassify}}", array[i].typename)
            .replaceAll("{{id}}", array[i].id);
        template += CourseClassifyTemplate;
    }

    courseLabelContainer.append(template);

}

//渲染课程
function applyCourses(result) {
    let coursesContainer = $(".courses");

    coursesContainer.html("");

    let array = result.data;

    let template = "";
    for (let i = 0; i < array.length; i++) {
        if (array[i].charge == 0) {
            template += $(".CourseFreeTemplate").html().replaceAll("{{courseId}}", array[i].id)
                .replaceAll("{{img_url}}", array[i].imgUrl)
                .replaceAll("{{synopsis}}", array[i].synopsis);

        } else {
            template += $(".CourseChargeTemplate").html().replaceAll("{{courseId}}", array[i].id)
                .replaceAll("{{img_url}}", array[i].imgUrl)
                .replaceAll("{{synopsis}}", array[i].synopsis);
        }
    }

    coursesContainer.append(template);


}


//点击全部课程
function onAll() {
    $("#charge").removeClass("active");
    $("#free").removeClass("active");
    courseClassifyId = null;
    charge = null;
    state = 0;
    getCourses();
}

//点击课程类型
function onCharge(type) {
    charge = type;
    if (charge==0){
        $("#charge").removeClass("active");
        $("#all").removeClass("active");
        $("#free").addClass("active");
    }
    if (charge==1){
        $("#free").removeClass("active");
        $("#all").removeClass("active");
        $("#charge").addClass("active")
    }
    getCourses();
}

//点击课程分类
function onCourseClass(obj) {
    let classId = $(obj).attr("value");
    courseClassifyId = classId;
    getCourses();
}

//点击已上线课程
function onState(type) {
    state = type;
    getCourses();
}


//点击课程
function onCourse(obj){
    let courseId = $(obj).attr("value");

    location.href = "course_detail.html?" + courseId;
}

